package security;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PublicKey;
import java.security.Security;

import javax.crypto.SecretKey;

import utils.Base64Processing;
import aiac.security.ProviderAIAC;

public class Hash {
	
	static{
		Security.addProvider(new ProviderAIAC());
	}

	public static String getStringHash(String toHash){
		try {
			MessageDigest sha = MessageDigest.getInstance("SHA-256", "ProviderAIAC");
			
			byte[] encodedToHash = toHash.getBytes("UTF-8");
			
			byte[] hashedString = sha.digest(encodedToHash);
			sha.reset();
			
			return Base64Processing.encodeData(hashedString);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		return null;
	}	
	
	public static String getKeysHash(SecretKey sessionKey, PublicKey clientPublic){
		try {
			MessageDigest sha = MessageDigest.getInstance("SHA-256", "ProviderAIAC");
			
			byte[] sessionKeyBytes = sessionKey.getEncoded();
			byte[] publicKeyBytes = clientPublic.getEncoded();
			
			sha.update(sessionKeyBytes);
			
			byte[] hashedString = sha.digest(publicKeyBytes);
			sha.reset();
			
			return Base64Processing.encodeData(hashedString);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
		}
		
		return null;
	}
}
